package com.woniuxy.purchase.handler;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMateObjectHandler implements MetaObjectHandler {


    /**
     * 添加时  自动填充
     * @param metaObject
     */
    @Override

    public void insertFill(MetaObject metaObject) {
        log.info("mybatisplus公共字段填充[insert]...");
        metaObject.setValue("createTime", DateTime.now().toString());//创建时间
        metaObject.setValue("updateTime", DateTime.now().toString());//修改时间
        metaObject.setValue("createUser",  SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());//创建人ID
        metaObject.setValue("updateUser",  SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());//修改人ID
    }
    /**
     * 更新时 自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("mybatisplus公共字段填充[update]...");
        metaObject.setValue("updateTime", LocalDateTime.now().toString());//修改时间
        metaObject.setValue("updateUser",  SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());//修改人ID
    }

    public static String getAccount(){
        SecurityContextHolder securityContextHolder = new SecurityContextHolder();
        log.info("当前登录用户,{}",SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        return  SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
    }
}